package br.com.seosoft.simplecalcfinan;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;
import br.com.seosoft.simplecalcfinan.adapters.AdapterListaSms;
import br.com.seosoft.simplecalcfinan.bancoDados.BancoDados;
import br.com.seosoft.simplecalcfinan.utils.BancosSMS;
import br.com.seosoft.simplecalcfinan.utils.IBancos;
import br.com.seosoft.simplecalcfinan.utils.Sms;

import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

public class LerSmsAntigos extends ActivyGeral {

	private List<String> listaSmsAntigos = new ArrayList<String>();
	private ListView listView;
	private ActionMode mActionMode = null;
	private AdapterListaSms adapter;
	private boolean removerCheckeds = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.ler_sms_antigos);

		listView = (ListView) findViewById(R.id.listaDeSms);

		taskSmsAntigos();
	}

	private void taskSmsAntigos() {

		new TaskLerSmsAntigos().execute();

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;

		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	class TaskLerSmsAntigos extends AsyncTask<Void, Void, List<String>> {

		private Sms sms;
		private List<String> listaSmsAntigosAux = new ArrayList<String>();
		private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			// Inicia leitura do SMS
			progressDialog = new ProgressDialog(LerSmsAntigos.this);

			progressDialog.setMessage(getResources().getString(
					R.string.carregandoArquivo));

			progressDialog.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss(DialogInterface dialog) {
					// TODO Auto-generated method stub
					cancel(true);

				}
			});

			progressDialog.show();

		}

		@Override
		protected List<String> doInBackground(Void... params) {
			// TODO Auto-generated method stub

			// Recebe lista dos SMS antigos
			if (!isCancelled()) {
				sms = new Sms();
				listaSmsAntigosAux = sms.getSmsAntigos(LerSmsAntigos.this);

			}

			if (isCancelled()) {
				return null;
			}

			return listaSmsAntigosAux;
		}

		@Override
		protected void onPostExecute(List<String> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			progressDialog.dismiss();

			List<IBancos> listaDebanco = new ArrayList<IBancos>();

			if (!isCancelled()) {

				IBancos[] bancos = new IBancos[result.size()];

				for (int i = 0; i < result.size(); i++) {

					bancos[i] = new BancosSMS(result.get(i), "000").getBanco();

					// !!!IMPORTANT verifica se o SMS esta OK
					if (bancos[i] != null) {

						if (bancos[i].getData() != null
								&& bancos[i].getDescricao() != null
								&& bancos[i].getValor() != null) {

							Log.v(geral.LogCat,
									"SMS BANCO: " + bancos[i].getNomebanco());

							listaDebanco.add(bancos[i]);

						}

					}

				}

				adapter = new AdapterListaSms(LerSmsAntigos.this, listaDebanco);

				listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
				listView.setFocusable(false);
				listView.setAdapter(adapter);
				listView.setFastScrollEnabled(true);

				listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {

						adapter.toggleChecked(arg2);
						Toast.makeText(
								getApplicationContext(),
								"Item: " + arg2 + " Total: "
										+ adapter.getCheckedItemCount(),
								Toast.LENGTH_SHORT).show();

						if (adapter.getCheckedItemCount() == 0) {

							if (mActionMode != null) {
								mActionMode.invalidate();
								mActionMode.finish();

							}

						} else if (adapter.getCheckedItemCount() > 0) {

							if (mActionMode != null) {

								mActionMode.invalidate();
							} else {
								mActionMode = getSherlock().startActionMode(
										new ActionModeAdapter());
								Log.v(geral.LogCat, "Criado Action menu");
							}
						}
					}
				});

			} else {
				listaSmsAntigos = null;
			}

		}

	}

	// CLASS ACTION MODE

	private final class ActionModeAdapter implements ActionMode.Callback {

		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {
			// TODO Auto-generated method stub

			mActionMode = mode;

			MenuInflater inflater = mode.getMenuInflater();
			inflater.inflate(R.menu.menu_import_sms, menu);

			return true;
		}

		@Override
		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {

			// TODO Auto-generated method stub

			menu.findItem(R.id.menuDropDownItens).setTitle(
					adapter.getCheckedItemCount() + " - "
							+ getString(R.string.selecionados));

			mActionMode = mode;
			return true;
		}

		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {

			mActionMode = mode;
			// TODO Auto-generated method stub

			switch (item.getItemId()) {

			case R.id.menuItemMarcarTudo:

				for (int i = 0; i < adapter.getCount(); i++) {

					listView.setItemChecked(i, true);
					adapter.setChecked(i, true);

				}

				mode.invalidate();

				return true;

			case R.id.menuItemDesmarcarTudo:

				for (int i = 0; i < adapter.getCount(); i++) {

					listView.setItemChecked(i, false);
					adapter.setChecked(i, false);

				}
				mode.invalidate();

				return true;

			case R.id.menuItemImportar:

				inserirSmsSelecionados();
				return true;

			default:

				return false;
			}

		}

		@Override
		public void onDestroyActionMode(ActionMode mode) {
			// TODO Auto-generated method stub
			mActionMode = null;
			taskSmsAntigos();
			if (removerCheckeds == false) {

			} else {

				// adapter.removerItens();
				// listView.clearChoices();
				// removerCheckeds = false;

			}

		}

	}

	private void inserirSmsSelecionados() {

		new threadInserirSMS().execute("");
	}

	// CLASS RECEBE THREAD SMS
	private class threadInserirSMS extends

	AsyncTask<String, Void, IBancos> {

		String error;
		IBancos banco;
		int id;
		private ProgressDialog progressDialog;
		BancoDados bd;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub

			bd = new BancoDados(LerSmsAntigos.this, false);
			super.onPreExecute();
			progressDialog = new ProgressDialog(LerSmsAntigos.this);
			progressDialog.setMessage(getString(R.string.carregando));
			progressDialog.show();

		}

		@Override
		protected IBancos doInBackground(String... smsMensagem) {

			bd.setPastaSms();
			id = bd.getPastaSMSId();
			SimpleDateFormat formatarDataTotal = new SimpleDateFormat(
					"yyyy-MM-dd", Locale.getDefault());

			for (int i = 0; i < adapter.getCount(); i++) {

				if (adapter.isChecked(i)) {
					banco = adapter.getItem(i);

					// VERIFICA SE DEBITO OU RECEITA

					if (banco != null) {

						String dataFormatada = formatarDataTotal.format(banco
								.getData());

						if (banco.getDescricao() != null
								& banco.getValor() != null
								& banco.getData() != null) {

							bd.GravaRegistroContas(String.valueOf(id), banco
									.getDescricao(), banco.getValor()
									.toString(), dataFormatada);

						}

					}
				}

			}

			return banco;

		}

		@Override
		protected void onPostExecute(IBancos result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			AlertDialog.Builder builder = new AlertDialog.Builder(
					LerSmsAntigos.this);

			builder.setIcon(android.R.drawable.ic_menu_info_details);
			builder.setTitle("SMS");

			builder.setMessage("Foram importados "
					+ adapter.getCheckedItemCount() + " SMS.");
			builder.setNeutralButton("OK", null);

			AlertDialog dialogo = builder.create();
			dialogo.show();

			removerCheckeds = true;
			mActionMode.finish();
			progressDialog.dismiss();

		}

	}

}
